# 创建时间：2025/5/4 星期日 16:33
# 创建人：李德才

print("====================普通实现方式=============================")


def cooking(func):
    def do_cooking():
        print("我负责做")
        func()
        print("我负责洗")

    return do_cooking


def eat():
    print("我开始吃")


do_cooking_result = cooking(eat)
do_cooking_result()

print("====================装饰器实现方式=============================")


def cooking(func):
    def do_cooking():
        print("我负责做")
        func()
        print("我负责洗")

    return do_cooking


@cooking
def eat():
    print("我开始吃")


eat()
print(eat.__name__)  # 输出：do_cooking

print("====================包装函数的名称=============================")

from functools import wraps


def cooking(func):
    @wraps(func)  # 将原函数的名称和文档复制到包装函数中
    def do_cooking():
        print("我负责做")
        func()
        print("我负责洗")

    return do_cooking


@cooking
def eat():
    print("我开始吃")


eat()
print(eat.__name__)  # 输出：do_cooking

print("====================带参数的装饰器=============================")
from functools import wraps


def cooking(func):
    @wraps(func)
    def do_cooking(*args, **kwargs):
        print("我负责做")
        func(*args, **kwargs)
        print("我负责洗")

    return do_cooking


@cooking
def eat(food):
    print(f"我开始吃{food}")


eat("汉堡")

print("====================使用类作为装饰器=============================")

import time


class Logs(object):
    def __init__(self, log_path="log.txt", level="INFO"):
        self.log_path = log_path
        self.level = level

    """ __call__ 方法是一个特殊的方法，它允许一个类的实例像函数一样被调用 """

    def __call__(self, func):
        @wraps(func)
        def write_logging(*args, **kwargs):
            print("记录日志，时间是：%s" % time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()))
            func(*args, **kwargs)

        return write_logging


@Logs(log_path="log2.txt", level="INFO")
def add(x, y):
    print(x + y)


add(1, 2)
